Longest Substring with At Most Two Distinct Characters

Given a string, find the length of the longest substring T that contains at most 2 distinct characters.

For example, Given s = "eceba",

T is "ece" which its length is 3.

Solution:

  1. public class Solution {
  2. public int lengthOfLongestSubstringTwoDistinct(String s) {
  3. if (s == null) return 0;
  4. int i = 0; // slow pointer
  5. int j = 0; // fast pointer
  6. int max = 0;
  7. // use a map to track the char and its count
  8. Map<Character, Integer> map = new HashMap<Character, Integer>();
  9. while (j < s.length()) {
  10. char ch = s.charAt(j);
  11. if (map.size() < 2 || map.containsKey(ch)) {
  12. // less than 2 distinct chars or the char is in the map already
  13. // put it to the map and update the count
  14. map.put(ch, map.containsKey(ch) ? map.get(ch) + 1: 1);
  15. // update the max
  16. max = Math.max(max, j - i + 1);
  17. j++;
  18. } else {
  19. // we keep removing the old chars from the map
  20. // till we only have one distinct char
  21. while (map.size() == 2) {
  22. ch = s.charAt(i);
  23. map.put(ch, map.get(ch) - 1);
  24. if (map.get(ch) == 0)
  25. map.remove(ch);
  26. i++;
  27. }
  28. }
  29. }
  30. return max;
  31. }
  32. }